package com.renrencai.quartz.schedule;

import com.alibaba.fastjson.util.TypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class HotSearchJob {

    private static final String sql = "SELECT \n" +
            "  keyword,\n" +
            "  SUM(search_number) \n" +
            "FROM\n" +
            "  p_app_historysearch \n" +
            "GROUP BY keyword \n" +
            "ORDER BY SUM(search_number) DESC\n" +
            " LIMIT 8 ";

    private static final String insertSql = " INSERT INTO p_app_topsearch (keyword) VALUES (?) ";

    @Autowired
    @Qualifier("rrcJdbcTemplate")
    JdbcTemplate rrc;

    @Scheduled(cron = "0 0/15 * * * *")
    public void run() {
        List<Map<String, Object>> list = rrc.queryForList(sql);
        System.out.println(LocalDateTime.now());
        List<String> keywordList = list.stream()
                .map(e -> TypeUtils.castToString(e.get("keyword")))
                .distinct()
                .limit(8)
                .collect(Collectors.toList());

        if (keywordList.size() == 0) {
            return;
        }

        if (keywordList.size() >= 8) {
            List<Object[]> saveList = new ArrayList<>();

            for (String s : keywordList) {
                saveList.add(new Object[]{s});
            }
            rrc.update("  truncate table p_app_topsearch  ");
            rrc.batchUpdate(insertSql, saveList);
        } else {
            //旧得热门搜索
            List<String> oldKeyWordList = rrc.queryForList(" SELECT keyword FROM p_app_topsearch ", String.class);

            keywordList.removeAll(oldKeyWordList);

            if (keywordList.size() > 0) {
                List<Object[]> saveList = new ArrayList<>();
                for (String s : keywordList) {
                    saveList.add(new Object[]{s});
                }
                //要删除的记录
                rrc.update(" delete from p_app_topsearch order by id desc limit ? ", keywordList.size());
                rrc.batchUpdate(insertSql, saveList);
            }
        }
    }
}
